<template>
  <div>
    <en-table-layout toolbar pagination :loading="loading" :tableData="tableData" @selection-change="handleSelectionChange">
      <div slot="toolbar" class="inner-toolbar">
        <div class="toolbar-btns">
          <el-button size="mini" type="primary" v-if="checkPermission(['order:add'])"
            @click="handleAdd">创建订单</el-button>
          <el-button size="mini" type="primary" v-if="type === 'TO_B' && checkPermission(['order:outbound'])"
            @click="batchOutbound(multipleSelection.map(order => order.id))">批量出库</el-button>
        </div>
        <div class="toolbar-search">
          <en-table-search @search="searchEvent" @advancedSearch="advancedSearchEvent" advanced advancedWidth="465"
            placeholder="请输入订单编号">
            <template slot="advanced-content">
              <el-form ref="advancedForm" :model="advancedForm" label-width="80px">
                <el-form-item label="订单状态">
                  <el-select v-model="advancedForm.status" clearable>
                    <el-option label="待提交" value="WAIT_SUBMIT" />
                    <el-option label="待审核" value="WAIT_AUDIT" />
                    <el-option label="审核驳回" value="AUDIT_REJECT" />
                    <el-option label="待出库" value="WAIT_WAREHOUSE_OUT" v-if="type === 'TO_B'" />
                    <el-option label="待发货" value="WAIT_SHIP" v-if="type === 'TO_B'"/>
                    <el-option label="已完成" value="COMPLETE" />
                  </el-select>
                </el-form-item>
                <el-form-item label="支付状态">
                  <el-select v-model="advancedForm.payment_status" clearable>
                    <el-option label="未支付" value="NOT_PAY" />
                    <el-option label="已支付" value="PAY" />
                  </el-select>
                </el-form-item>
                <el-form-item label="销售渠道">
                  <el-select v-model="advancedForm.source_id" clearable>
                    <el-option label="平台" value="0" />
                    <el-option v-for="item in clientList" :key="item.client_id" :label="item.client_id" :value="item.client_id"/>
                  </el-select>
                </el-form-item>
                <el-form-item label="下单时间">
                  <el-date-picker v-model="advancedForm.order_time" type="daterange" align="center" :default-time="['00:00:00', '23:59:59']"
                    :editable="false" unlink-panels range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期">
                  </el-date-picker>
                </el-form-item>
              </el-form>
            </template>
          </en-table-search>
        </div>
      </div>
      <template slot="table-columns">
        <el-table-column type="selection" width="55" :selectable="canWarehouseOut" />
        <el-table-column prop="sn" label="订单编号">
          <template slot-scope="scope">
            <router-link
              style="color: #409eff;"
              :to="{ name: 'orderDetail', params: { id: scope.row.id } }">
              {{ scope.row.sn }}
            </router-link>
          </template>
        </el-table-column>
        <el-table-column label="下单用户">
          <template slot-scope="scope">{{ scope.row.owner_name }}</template>
        </el-table-column>
        <el-table-column label="下单时间">
          <template slot-scope="scope">{{ scope.row.order_time | unixToDate }}</template>
        </el-table-column>
        <el-table-column prop="warehouse_name" label="仓库名称">
          <template slot-scope="scope">{{ scope.row.warehouse_name }}</template>
        </el-table-column>
        <el-table-column prop="warehouse_name" label="所属部门">
          <template slot-scope="scope">{{ scope.row.dept_name }}</template>
        </el-table-column>
        <el-table-column prop="delivery_type_text" label="配送方式" v-if="type === 'TO_B'">
          <template slot-scope="scope">{{ scope.row.delivery_type_text }}</template>
        </el-table-column>
        <el-table-column prop="status" label="实付金额">
          <template slot-scope="scope">{{ '￥' + scope.row.pay_price }}</template>
        </el-table-column>
        <el-table-column prop="status" label="订单状态">
          <template slot-scope="scope">{{ scope.row.status_text }}</template>
        </el-table-column>
        <el-table-column prop="status" label="支付状态">
          <template slot-scope="scope">{{ scope.row.payment_status_text }}</template>
        </el-table-column>
        <el-table-column prop="status" label="销售渠道">
          <template slot-scope="scope">{{ scope.row.source === 'Internal' ? '平台' : scope.row.source_id }}</template>
        </el-table-column>
        <el-table-column label="操作" width="250">
          <template slot-scope="scope">
            <el-button size="mini" type="success" v-if="scope.row.allowable.submit && checkPermission(['order:submit'])"
                       @click="handleSubmit(scope.row.id)">提交</el-button>
            <el-button size="mini" type="danger" v-if="scope.row.allowable.withdraw && checkPermission(['order:withdraw'])"
                       @click="handleWithdraw(scope.row.id)">撤回</el-button>
            <el-button size="mini" v-if="scope.row.allowable.edit && checkPermission(['order:edit'])"
                       @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="success" v-if="scope.row.allowable.audit && checkPermission(['order:audit'])"
                       @click="handleAudit(scope.row)">审核</el-button>
            <el-button size="mini" type="primary" v-if="scope.row.allowable.payment && checkPermission(['order:payment'])"
                       @click="handlePayment(scope.row.id)">设为已支付</el-button>
            <el-button size="mini" type="primary" v-if="scope.row.allowable.warehouse_out && checkPermission(['order:outbound'])"
                       @click="batchOutbound([scope.row.id])">出库</el-button>
          </template>
        </el-table-column>
      </template>
      <el-pagination slot="pagination" v-if="pageData" @size-change="handlePageSizeChange"
                     @current-change="handlePageCurrentChange" :current-page="pageData.page_no" :page-sizes="[10, 20, 50, 100]"
                     :page-size="pageData.page_size" layout="total, sizes, prev, pager, next, jumper" :total="pageData.data_total">
      </el-pagination>
    </en-table-layout>
  </div>
</template>

<script>
import * as API_order from '@/api/order'
import * as API_OAuth2Client from '@/api/oauth2Client'
import Storage from '@/utils/storage'

export default {
  name: 'orderList',
  data() {
    return {
      /** 列表loading状态 */
      loading: false,

      /** 列表参数 */
      params: {
        page_no: 1,
        page_size: 10,
        ...this.$route.query
      },
      cancelpopup: false,
      cancelLister: '',
      /** 列表数据 */
      tableData: [],

      /** 列表分页数据 */
      pageData: [],

      /** 高级搜索数据 */
      advancedForm: {
      },

      /** 表格最大高度 */
      tableMaxHeight: (document.body.clientHeight - 54 - 34 - 50 - 15),

      accessToken: Storage.getItem('seller_access_token'),
      multipleSelection: [],
      type: '',
      clientList: ''
    }
  },
  mounted() {
    this.GET_OrderList()
    this.GET_ClientList()
  },
  activated() {
    delete this.params.market_enable
    this.params = {
      ...this.params,
      ...this.$route.query
    }
    this.GET_OrderList()
    window.onresize = this.countTableHeight
  },
  beforeRouteUpdate(to, from, next) {
    delete this.params.market_enable
    this.params = {
      ...this.params,
      ...this.$route.query
    }
    this.GET_OrderList()
    next()
  },
  methods: {
    batchOutbound(orderIds) {
      if (orderIds.length === 0) {
        this.$message.error('请选择订单!')
        return
      }

      this.$router.push({
        name: 'orderOutbound',
        params: { orderIds: orderIds }
      })
    },
    /** 计算高度 */
    countTableHeight() {
      this.tableHeight = (document.body.clientHeight - 54 - 35 - 50)
    },
    /** 多选改变 */
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    /** 新增 */
    handleAdd() {
      this.$router.push({
        name: 'orderAdd',
        params: { callback: this.GET_OrderList },
        query: { type: this.type }
      })
    },
    /** 是否可以出库 */
    canWarehouseOut(row) {
      return row.allowable.warehouse_out
    },

    /** 分页大小发生改变 */
    handlePageSizeChange(size) {
      this.params.page_size = size
      this.GET_OrderList()
    },
    /** 分页页数发生改变 */
    handlePageCurrentChange(page) {
      this.params.page_no = page
      this.GET_OrderList()
    },

    /** 搜索事件触发 */
    searchEvent(data) {
      this.params = {
        ...this.params,
        keywords: data
      }
      this.params.page_no = 1
      delete this.params.order_status
      Object.keys(this.advancedForm).forEach(key => delete this.params[key])
      this.GET_OrderList()
    },

    /** 高级搜索事件触发 */
    advancedSearchEvent() {
      this.params = {
        ...this.params,
        ...this.advancedForm
      }
      this.params.page_no = 1
      delete this.params.start_time
      delete this.params.end_time
      if (this.advancedForm.order_time) {
        this.advancedForm.order_time[0] = this.advancedForm.order_time[0].getTime() / 1000
        this.advancedForm.order_time[1] = this.advancedForm.order_time[1].getTime() / 1000
      }
      delete this.params.keywords
      this.GET_OrderList()
    },

    /** 编辑订单 */
    handleEdit(order) {
      this.$router.push({
        name: 'orderEdit',
        params: { id: order.id, callback: this.GET_OrderList }
      })
    },
    /** 审核订单 */
    handleAudit(order) {
      this.$router.push({
        name: 'orderDetail',
        params: { id: order.id, callback: this.GET_OrderList }
      })
    },
    /** 订单设为已支付 */
    async handlePayment(id) {
      // 二次确认
      await this.$confirm(`确认要设为已支付吗?`, '提示')
      // 发起修改
      await API_order.payment(id)
      this.$message.success('操作成功！')
      // 刷新列表
      this.GET_OrderList()
    },
    /** 提交订单 */
    async handleSubmit(id) {
      // 发起修改
      await API_order.submit(id)
      this.$message.success('操作成功！')
      // 刷新列表
      this.GET_OrderList()
    },
    /** 撤回订单 */
    async handleWithdraw(id) {
      // 发起修改
      await API_order.withdraw(id)
      this.$message.success('操作成功！')
      // 刷新列表
      this.GET_OrderList()
    },

    GET_OrderList() {
      this.loading = true
      this.params.type = this.type
      API_order.getOrderList(this.params).then(response => {
        this.loading = false
        this.tableData = response.data
        this.pageData = {
          page_no: response.page_no,
          page_size: response.page_size,
          data_total: response.data_total
        }
      })
    },

    GET_ClientList() {
      API_OAuth2Client.getList({ page_size: -1 }).then(response => {
        this.clientList = response.data
      })
    }
  },
  watch: {
    $route: {
      immediate: true,
      handler(newVal) {
        if (newVal.name === 'order') {
          this.type = 'TO_B'
        }
        if (newVal.name === 'retailOrder') {
          this.type = 'TO_C'
        }
        this.GET_OrderList()
      }
    }
  }
}
</script>

<style type="text/scss" lang="scss" scoped>
.container {
  padding: 10px 10px 0 10px;
}

/deep/ .el-table {
  min-height: auto !important;
}

/deep/ div.toolbar {
  height: 70px;
  padding: 20px 0;
}

/* 工具条*/
.inner-toolbar {
  display: flex;
  width: 100%;
  justify-content: space-between;
  padding: 0 20px;
}

.empty-block {
  position: relative;
  min-height: 60px;
  line-height: 60px;
  text-align: center;
  width: 262%;
  font-size: 14px;
  color: #606266;
}

/*表格信息*/
.my-table-out {
  white-space: nowrap;
  overflow-y: scroll;
  overflow-x: hidden;
  text-overflow: ellipsis;
  width: 100%;
  max-height: 800px;
  margin: 0 10px;
  min-height: 480px !important;
  background: #fff;
}

.my-table {
  width: 100%;
  margin-bottom: 40px;
  background: #fff;
  border-collapse: collapse;
  font-family: Helvetica Neue, Helvetica, PingFang SC, Hiragino Sans GB, Microsoft YaHei, Arial, sans-serif;
  font-size: 14px;
  font-bold: 700;

  .bg-order {
    background: #FAFAFA;
  }

  thead {
    th {
      padding: 10px 0;
      border: 1px solid #ebeef5;
      border-collapse: collapse;
      color: #909399;
    }

    th.shoplist-header {
      padding: 10px 20px;
      display: flex;
      flex-direction: row;
      flex-wrap: nowrap;
      justify-content: space-between;
      align-items: center;
    }
  }

  tbody {
    margin-top: 10px;

    td {
      border: 1px solid #ebeef5;
      border-collapse: collapse;
      text-align: center;
      padding: 0;
    }

    td:first-child {
      text-align: left;
    }

    td:not(:first-child) {
      padding: 3px;
    }

    td.shoplist-content-out {
      padding-left: 20px;
    }

    /*商品信息*/
    p.shoplist-content:not(:last-child) {
      border-bottom: 1px solid #ebeef5;
      border-collapse: collapse;
    }

    p.shoplist-content {
      margin: 0;
      padding: 0 20px;
      box-sizing: padding-box;
      display: flex;
      flex-direction: row;
      flex-wrap: nowrap;
      justify-content: space-between;
      align-items: center;

      .goods-info {
        display: flex;
        flex-direction: row;
        flex-wrap: nowrap;
        justify-content: flex-start;
        align-items: center;
        padding: 10px 0;

        img {
          display: block;
          margin-right: 10px;
        }

        a {
          display: block;
          color: #409EFF;
        }
      }
    }

    div.order-money {
      display: flex;
      flex-direction: column;
      flex-wrap: nowrap;
      justify-content: center;
      align-items: center;

      span {
        display: inline-block;
        padding: 5px;
      }

      span.order-amount {
        color: red;
      }
    }
  }

  /* 商品图片 */
  .goods-image {
    width: 50px;
    height: 50px;
  }

  /** 交易快照 */
  .trade-record {
    display: inline-block;
    margin-right: 50px;
  }
}

/*分页信息*/
section>div {
  position: relative;
}

.el-pagination {
  text-align: right;
  width: 100%;
  background: #ffffff;
  height: 100px;
  padding: 5px 20px;
  margin: 0 10px;
}

.exprot-tip {
  margin-left: 5px;
  color: red;
  font-size: 12px;
}
</style>

